/**
 * 公共Socket类
 * @Swyin 
 * 2015-8-25
 */
class Socket
{
    private static _instance: Socket;
    private static _allowInstance: Boolean;
    private _socket: egret.WebSocket;

    public constructor()
    {
        if ( !Socket._allowInstance )
            return;
    }

    public static getInstance(): Socket
    {
        if ( this._instance == null )
        {
            this._allowInstance = true;
            this._instance = new Socket();
            this._allowInstance = false;
        }
        return this._instance;
    }

    public addSocket(): void
    {
        this._socket = new egret.WebSocket();
        //设置数据格式为二进制，默认为字符串
        this._socket.type = egret.WebSocket.TYPE_STRING;
        //添加收到数据侦听，收到数据会调用此方法
        this._socket.addEventListener( egret.ProgressEvent.SOCKET_DATA, this.onReceiveMessage, this );
        //添加链接打开侦听，连接成功会调用此方法
        this._socket.addEventListener( egret.Event.CONNECT, this.onSocketOpen, this );
        //添加链接关闭侦听，手动关闭或者服务器关闭连接会调用此方法
        this._socket.addEventListener( egret.Event.CLOSE, this.onSocketClose, this );
        //添加异常侦听，出现异常会调用此方法
        this._socket.addEventListener( egret.IOErrorEvent.IO_ERROR, this.onSocketError, this );
        //连接服务器
        this._socket.connect( "112.74.192.62", 1947 );
    }

    private onSocketOpen(): void
    {
        GameBus.getInstance().dispatchEvent( new SocketEvent( SocketEvent.CONNECT ) );
    }

    private onReceiveMessage( e: egret.Event ): void
    {
        ProtocolInfo.getInstance().handleProtocolInfo( this._socket.readUTF() );
    }

    private onSocketClose(): void
    {
        GameBus.getInstance().dispatchEvent( new SocketEvent( SocketEvent.CLOSE ) );
    }

    private onSocketError(): void
    {
        GameBus.getInstance().dispatchEvent( new SocketEvent( SocketEvent.IO_ERROR ) );
    }

    /**
     * 发送协议
     * @protocol:协议号
     * @data：数据object
     */
    public sendProtocol( protocol: number, data: Object ): void
    {
        var data: Object = { protocol: protocol, data: data };
        var json = JSON.stringify( data );
        this._socket.writeUTF( json );
    }

    public sendHeartbeat(): void
    {
        this._socket.writeUTF( 'heartbeat' );
    }
}
